package org.spring.boot.rabbitmq.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.boot.rabbitmq.conf.RabbitConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author: eastcom
 * @desc: 发送消息控制层
 **/
@RestController
@RequestMapping("/rabbitmq")
public class SendMessageWebService {

	private static final Logger log = LoggerFactory.getLogger(SendMessageWebService.class);


	@Autowired
	private RabbitTemplate dlRabbitTemplate;

	@GetMapping
	@RequestMapping("send/dead/letter/message/{hour}/{minute}")
	public void deadLetterMessage(@PathVariable("hour") final int hour, @PathVariable("minute") final int minute){
		final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		this.dlRabbitTemplate.convertAndSend(RabbitConfig.REGISTER_DELAY_EXCHANGE,
				RabbitConfig.DELAY_ROUTING_KEY, "DEAL LETTER MESSAGE"+sdf.format(Calendar.getInstance().getTime()),  new MessagePostProcessor(){

					@Override
					public Message postProcessMessage(Message message) throws AmqpException {
						Date expirationDate;
						Calendar calendar = Calendar.getInstance();
						calendar.set(2019,04,06, hour, minute,23);
						expirationDate = calendar.getTime();

						log.info("time is {}", sdf.format(expirationDate));
						/* 计算差为毫秒 */
						Long timeBetween = (expirationDate.getTime() - (new Date()).getTime());
						if(timeBetween <= 0){
							log.info("消息没有时间延迟");
							timeBetween = 0L;
						}
						log.info("timeBetween is {}", timeBetween);
						/* 设置的时间单位为毫秒 */
						message.getMessageProperties().setExpiration(timeBetween.toString());
						return message;
					}
				});
	}
}
